import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
function Square(props) {
    return (
        <button
            className={(props.isCurrent ? "active " : "") + (props.isWinner ? "winner" : "") + " square"}
            onClick={props.onClick}>
            {props.value}
        </button>
    );
}
class Board extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            boardArr: Array(9).fill(null)
        };
    }

    renderSquare(i) {
        const isWinner = this.props.winLine.includes(i);
        const isCurrent = this.props.currentIndex === i;
        return (
            <Square
                isCurrent={isCurrent}
                isWinner={isWinner}
                value={this.props.squares[i]}
                onClick={() => this.props.onClick(i)}
            />
        );
    }

    render() {
        // const winner = calculateWinner(this.state.squares);
        // const status = winner ? 'Winner: ' + winner : "Next player: " + (this.state.xIsNext ? "X" : "O");
                // <div className="status">{status}</div>
        let ele = [];
        for (let i = 0; i < this.state.boardArr.length; i += 3) {
            ele = ele.concat(
                <div className="board-row" key={i}>
                    {this.renderSquare(i)}
                    {this.renderSquare(i + 1)}
                    {this.renderSquare(i + 2)}
                </div>
            );
        }
        return <div className="board-box">{ele}</div>;
    }
}

class Game extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            history: [
                {
                    squares: Array(9).fill(null),
                    lastStepArrow: [],
                    currentIndex: null,
                },
            ],
            sortType: "up",
            stepNumber: 0,
            xIsNext: true,
        };
    }
    render() {
        const history = this.state.history;
        const current = history[this.state.stepNumber];
        const { winner, line } = calculateWinner(current.squares);
        let status;
        if (winner) {
            status = "获胜者: " + winner;
        } else {
            status =
                this.state.stepNumber === current.squares.length
                    ? "该局平局，没有获胜者"
                    : "下一步玩家: " + (this.state.xIsNext ? "X" : "O");
        }
        let moves = history.map((step, move) => {
                      const desc = move
                          ? "移动到 #" + move + "(" + step.lastStepArrow[0] + "," + step.lastStepArrow[1] + ")"
                          : "回到开始";
                      return (
                          <li key={move}>
                              <button onClick={() => this.jumpTo(move)}>{desc}</button>
                          </li>
                      );
                  });
        if(this.state.sortType !== "up"){
            moves = moves.reverse();
        }
        return (
            <div className="game">
                <div className="game-board">
                    <Board
                        winLine={line}
                        currentIndex={current.currentIndex}
                        squares={current.squares}
                        onClick={i => this.handleClick(i)}
                    />
                </div>
                <div className="game-info">
                    <div className="game-notify">{status}</div>
                    <div className="game-title" onClick={() => this.handleSort()}>
                        历史记录: {this.state.sortType === "up" ? "降序" : "升序"}
                    </div>
                    <ol className="game-history">{moves}</ol>
                </div>
            </div>
        );
    }

    jumpTo(step) {
        this.setState({
            stepNumber: step,
            xIsNext: step % 2 === 0,
        });
    }
    handleSort(){
        console.log('???')
        this.setState({
            sortType: this.state.sortType === "up" ? "down": "up"
        });
    }
    handleClick(i) {
        const history = this.state.history.slice(0, this.state.stepNumber + 1);
        const current = history[history.length - 1];
        const squares = current.squares.slice();
        if (calculateWinner(squares).winner || squares[i]) {
            return;
        }
        squares[i] = this.state.xIsNext ? "X" : "O";
        this.setState({
            history: history.concat([
                {
                    squares: squares,
                    currentIndex: i,
                    lastStepArrow: [Math.floor(i / 3) + 1, (i % 3) + 1],
                },
            ]),
            stepNumber: history.length,
            xIsNext: !this.state.xIsNext,
        });
    }
}
function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return {
                winner: squares[a],
                line: lines[i],
            };
        }
    }
    return {
        winner: null,
        line: []
    };
}
// ========================================

ReactDOM.render(<Game />, document.getElementById("root"));
